package com.ceshiren.mini.service.impl;

import com.ceshiren.mini.dto.OperateJenkinsJobDTO;
import com.ceshiren.mini.dto.PlanTestCasesDTO;
import com.ceshiren.mini.entity.Plan;
import com.ceshiren.mini.entity.Record;
import com.ceshiren.mini.exception.ServiceException;
import com.ceshiren.mini.service.JenkinsService;
import com.ceshiren.mini.util.JenkinsUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
//http://127.0.0.1:8080/job/mini_job/config.xml

@Service
public class JenkinsServiceImpl implements JenkinsService {
    //jenkins地址
    @Value("${jenkins.url}")
    private String jenkinsUrl;
    //Jenkins用户
    @Value("${jenkins.user}")
    private String jenkinsUserName;
    //Jenkins密码
    @Value("${jenkins.pwd}")
    private String jenkinsPassword;
    @Value("${jenkins.job}")
    private String job;

    //Jenkins执行测试
    @Override
    public OperateJenkinsJobDTO runTask(Plan plan) {
        //Record record = new Record();
        //record.setPlanId();

        //job实体类
        OperateJenkinsJobDTO operateJenkinsJobDTO = new OperateJenkinsJobDTO();
        //放入url
        operateJenkinsJobDTO.setJenkinsUrl(jenkinsUrl);
        //用户名
        operateJenkinsJobDTO.setJenkinsUserName(jenkinsUserName);
        //用户密码
        operateJenkinsJobDTO.setJenkinsPassword(jenkinsPassword);
        //任务名称
        operateJenkinsJobDTO.setJob(job);


        HashMap<String, String> params = new HashMap<>();
        //Jenkins执行job命令 todo:
        params.put("testCommand", "/Users/gaigai/apache-maven-3.9.0/bin/mvn clean test " + plan.getCommand() + " allure:report");
        operateJenkinsJobDTO.setParams(params);
        System.out.println("Jenkins执行实体类" + operateJenkinsJobDTO);

        try {
            OperateJenkinsJobDTO jenkinsJobDTO = JenkinsUtil.buildWithXML(operateJenkinsJobDTO);
            //OperateJenkinsJobDTO{jenkinsUrl='http://127.0.0.1:8080/job/mini_job/', jenkinsUserName='root', jenkinsPassword='123456', job='mini_job', jobUrl='null', jobId=28, jobStatus='FAILURE', params={testCommand=-Dtest=com.ceshiren.num.SumTest#sumNum1,com.ceshiren.num.SumTest#sumNumError}}
            jenkinsJobDTO.setJenkinsUrl(operateJenkinsJobDTO.getJenkinsUrl());

        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
        return operateJenkinsJobDTO;
    }
}
